package com.ktjiaoyu.ktmall.service.impl;

import com.ktjiaoyu.ktmall.dao.CartDao;
import com.ktjiaoyu.ktmall.dao.impl.CartDaoImpl;
import com.ktjiaoyu.ktmall.entity.Cart;
import com.ktjiaoyu.ktmall.service.CartService;
import com.ktjiaoyu.ktmall.vo.CartVo;

import java.util.List;

public class CartServiceImpl implements CartService {
    private CartDao cartDao = new CartDaoImpl();
    @Override
    public List<CartVo> getCartList(String userId) {
        return cartDao.selectByUserId(userId);
    }

    @Override
    public List<CartVo> getItemsByIds(List<String> cartIds) {
        return cartDao.selectByIds(cartIds);
    }

    @Override
    public String addToCart(String userId, String productId, Integer quantity) {
        Cart existingCart = cartDao.selectByUserAndProduct(userId,productId);
        if (existingCart !=null){
            existingCart.setQuantity(existingCart.getQuantity()+quantity);
            if (cartDao.update(existingCart)>0){
                return existingCart.getId();
            }
            return null;
        }
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setQuantity(quantity);
        cart.setSelected(1);
        if (cartDao.insert(cart)>0){
            return cart.getId();
        }
        return null;
    }

    @Override
    public int getCartCount(String userId) {
        return cartDao.countByUserId(userId);
    }
}
